﻿using GalacticLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace GalacticClientGui
{



    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, IGalacticClientUI
    {

         delegate void UpdateTextCallback(string message);
         delegate void UpdateActiveRequestUi(DataRunRequest req);

         List<string> OutputLines;
         const int MaxOutputLines = 30;


         void Output(string s)
        {
           OutputTextbox.Dispatcher.Invoke(
            new UpdateTextCallback(this.UpdateTextbox),
            new object[] { s }
        );
        }

        void UpdateTextbox(string s)
         {
            if(OutputLines.Count == MaxOutputLines)
            {
                OutputLines.Remove(OutputLines.First());
            }
                OutputLines.Add(s);
                OutputTextbox.Text = String.Join(Environment.NewLine, OutputLines);
                OutputTextbox.ScrollToEnd();
            
            //  OutputTextbox.AppendText(s + Environment.NewLine);
            //  OutputTextbox.ScrollToEnd();
         }

         DataRunProcessor Processor;


        public MainWindow()
        {
            InitializeComponent();
            OutputLines = new List<string>();
            OutputLines.Capacity = MaxOutputLines;

            string config = File.ReadAllText("GalacticClientConfig.xml");
            Processor = new DataRunProcessor(config, this);

            AutoProcessCheckbox.IsChecked = Processor.AutoProcess;
            if (Processor.AutoProcess)
                Uri.IsEnabled = AutoProcessCheckbox.IsEnabled = false;

             Uri.Text = Processor.ServerUri.ToString();
             ClientUniqueId.Text = Processor.ClientUniqueId;
             string c = Processor.GetConfigString();

            Processor.OutputEvent += Output;
        }

        private void StartButtonClick(object sender, RoutedEventArgs e)
        {
            Processor.ServerUri = new Uri(Uri.Text);
            Processor.ClientUniqueId = ClientUniqueId.Text;
            Uri.IsEnabled = ClientUniqueId.IsEnabled = AutoProcessCheckbox.IsEnabled =  false;
            Processor.Start();
        }

        private void StopButtonClick(object sender, RoutedEventArgs e)
        {
            Uri.IsEnabled = ClientUniqueId.IsEnabled = AutoProcessCheckbox.IsEnabled = true;
            Processor.Stop();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Processor.Stop();
        }

        private void OutputTextbox_TextChanged(object sender, TextChangedEventArgs e)
        {
        

           
                /*
                 //get all the lines out as an arry
string[] lines = this.textBox.Lines;
You can then work with this array and set it back.

  this.textBox.Lines= newLinesArray;
This might not be the most elegant way, but it will remove the first line. EDIT: you don't need select, just using skip will be fine

    //number of lines to remove from the beginning
    int numOfLines = 30; 
    var lines = this.textBox1.Lines;
    var newLines = lines.Skip(numOfLines);

    this.textBox1.Lines = newLines.ToArray();
                 * */
        }

        private void SaveSettingsButtonClick(object sender, RoutedEventArgs e)
        {
            string settings = Processor.GetConfigString();
            File.WriteAllText("GalacticClientConfig.xml", settings);
            Output("Saved Settings");
        }

        private void AutoProcessCheckbox_Unchecked(object sender, RoutedEventArgs e)
        {
            Processor.AutoProcess = false;
        }

        private void AutoProcessCheckbox_Checked(object sender, RoutedEventArgs e)
        {
            Processor.AutoProcess = true;
        }

        void ExitIfNoPendingRunsCheck()
        {


            WorkingOnLabel.Content = "";

            if ((bool)ExitIfNoPendingRunsCheckbox.IsChecked)
            {
                Application.Current.Shutdown();
                return;
            }
        }

        public void NoPendingRuns()
        {
            Dispatcher.Invoke(
               ExitIfNoPendingRunsCheck);          
                
        }


        void StartingDataRunUpdateUi(DataRunRequest req)
        {
            if (req != null)
                WorkingOnLabel.Content = "[" + req.DataRunRequestId + "] " + req.Title;
     
        }


        public void StartingRun(DataRunRequest req)
        {
            Dispatcher.Invoke(
                new UpdateActiveRequestUi(StartingDataRunUpdateUi),
                new object[] {  req }
              );       
        }
    }
}
